package com.weight.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weight.controller.utils.Result;
import com.weight.dao.UserDao;
import com.weight.entity.User;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.flywaydb.core.internal.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.UUID;

@Service
public class UserService extends ServiceImpl<UserDao, User>{
    String codeTemp = "";
    @Autowired
    private JavaMailSender javaMailSender;

    public Result<Object> regist(User user) {
        if(!StringUtils.hasLength(user.getUsername())){
            return Result.error("用户名不能为空");
        }if(!StringUtils.hasLength(user.getPwd())){
            return Result.error("密码不能为空");
        }if (!StringUtils.hasLength(user.getPwd2())){
            return Result.error("确认密码不能为空");
        }if (!user.getPwd().equals(user.getPwd2())){
            return Result.error("确认密码和原密码不一样");
        }if (!StringUtils.hasLength(user.getEmail())){
            return Result.error("邮箱不能为空");
        }if (!user.getEmail().matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
            return Result.error("请输入正确的邮箱");
        }if (!StringUtils.hasLength(user.getCode())){
            return Result.error("验证码不能为空");
        }if (!codeTemp.equals(user.getCode())){
            return Result.error("验证码错误");
        }
        int count = count(new QueryWrapper<User>().eq("email",user.getEmail()));
        if (count>0) return Result.error("已经注册过了");
        //生成id
        user.setId(String.valueOf(UUID.randomUUID()).replaceAll("-",""));
        save(user);
        codeTemp = "";
        return Result.success(null,"注册成功");
    }

    //发送验证码FIWLVNTADOVRGHCS
    public Result sendCode(String email) {
        if (!StringUtils.hasLength(email)) return  Result.error("请输入正确的邮箱");
        if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) return Result.error("请输入正确的邮箱");
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("caozhou1926@163.com"); //发送者
        message.setTo(email);  //接受者
        message.setSubject("验证码");	//主题
        String code = MakeVerificationCode();
        message.setText("您好，您的邮箱验证码为:  "+ code + "\n"+"该验证码5分钟内有效，请勿泄露给他人");	//内容
        javaMailSender.send(message);
        return Result.success(null,"发送成功");
    }

    /**
     * 生成验证码
     */
    public String MakeVerificationCode(){
        StringBuilder code = new StringBuilder();
        for(int i =0;i<6;i++){code.append(new Random().nextInt(10));}
        codeTemp = code.toString();
        return code.toString();
    }

}
